package publisherSubscriber.examples;

import java.io.IOException;

import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ServantNotActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import corbaEventService.EventChannelImpl;


public class CorbaAPP {

	public static void main(String[] args) {

		try {
			if(args.length != 3){
				System.out.println("Usage: CorbaApp host port topicName");
				System.exit(1);
			}
			
			//RunDemon
			//Update /etc/hosts file for naming service
			Runtime.getRuntime().exec("orbd -ORBInitialPort "+args[1]+" -ORBInitialHost "+args[0]);  
			Thread.sleep(3000);			
			
			// Create Servant		
			EventChannelImpl channel =  new EventChannelImpl ();

			//Create ORB
			String arg[] = {"-ORBInitialPort","1050","-ORBInitialHost","localhost"};
			arg[1] = args[1];
			arg[3] = args[0];
			
			ORB orb = ORB.init(arg,null);
			
			//Get reference to rootpoa
			POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
		
			//Activate POAManager
			rootpoa.the_POAManager().activate();
			
			//Activate Servant and get its refernece
			Object ref = rootpoa.servant_to_reference(channel);
					
			//Get the root naming context
			Object objRef = orb.resolve_initial_references("NameService");
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
			
			//Bind the Servant
			NameComponent path[] = ncRef.to_name(args[2]);
			ncRef.rebind(path, ref);
			
			//Wait for client
			System.out.println("Waiting...");
			orb.run();
		
		} catch (InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AdapterInactive e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServantNotActive e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WrongPolicy e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotFound e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CannotProceed e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
